package xyz.renyumeng.xkm.user.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.renyumeng.xkm.exception.XkmException;
import xyz.renyumeng.xkm.model.shop.ProductTypeInfo;
import xyz.renyumeng.xkm.model.user.UserAddressInfo;
import xyz.renyumeng.xkm.result.Result;
import xyz.renyumeng.xkm.user.mapper.UserAddressInfoMapper;
import xyz.renyumeng.xkm.user.service.UserAddressInfoService;
import xyz.renyumeng.xkm.user.service.UserInfoService;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author renyumeng
 * @date Created in 9:53 2023/7/2
 */

@Service
@Transactional
public class UserAddressInfoServiceImpl extends ServiceImpl<UserAddressInfoMapper, UserAddressInfo> implements UserAddressInfoService {

    @Resource
    private UserInfoService userInfoService;

    @Override
    public Result<List<UserAddressInfo>> getAddressInfoByParentId(Long parentId) {
        LambdaQueryWrapper<UserAddressInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(UserAddressInfo::getParentId, parentId);
        List<UserAddressInfo> userAddressInfoList = baseMapper.selectList(qw);

        userAddressInfoList.forEach(productTypeInfo -> {
            Long productTypeInfoId = productTypeInfo.getId();
            boolean isChild = this.isChild(productTypeInfoId);

            productTypeInfo.setHasChildren(isChild);


        });
        return Result.ok(userAddressInfoList);
    }

    @Override
    public Result<UserAddressInfo> getUserAddressInfoByUserId(Long addressId) {
        UserAddressInfo userAddressInfo = this.getById(addressId);
        if (ObjectUtil.isEmpty(userAddressInfo)){
            throw new XkmException(201,"该地址不存在!");
        }
        Long userAddressParentId = userAddressInfo.getParentId();

        UserAddressInfo userParentAddress = this.getById(userAddressParentId);
        if (ObjectUtil.isEmpty(userParentAddress)){
            throw new XkmException(201,"该地址不存在!");
        }
        String userAddress = userParentAddress.getAddress() + ":" + userAddressInfo.getAddress();
        UserAddressInfo resultUserAddressInfo = BeanUtil.copyProperties(userParentAddress, UserAddressInfo.class);
        resultUserAddressInfo.setAddress(userAddress);
        resultUserAddressInfo.setHasChildren(true);

        return Result.ok(resultUserAddressInfo).message("查询用户地址信息成功!");
    }

    private boolean isChild(Long userAddressInfoId) {
        LambdaQueryWrapper<UserAddressInfo> qw = new LambdaQueryWrapper<>();
        qw.eq(UserAddressInfo::getParentId, userAddressInfoId);
        Integer count = baseMapper.selectCount(qw);
        return count > 0;
    }
}
